<template>
	<!-- //免费支付不显示页面 -->
	<view class="overflow-h" :style="{ '--themescolor': themes.color }">
		<view class="" v-if="!$u.test.isEmpty(payInfo.businessOrderNumberList)">
			<!-- 支付金额 -->
			<view class="bg-white w-100 text-center">
				<view class="font-24">
					<view class="font-28 w-100 h-80r flex-start pl-2" style="background: #FFF7ED;color: #D68652;">
						<text class="iconfont icon-laba1 mr-1" style="font-size: 32rpx;"></text>
						提交成功，请尽快付款，逾期未付款订单自动关闭
					</view>
					<view class="pt-3">
						<view class="line-clamp1"><ls-price :price="payInfo.amount" :options="{ is: 56,ds:32, iw: 'bold' }" /></view>
					</view>
					<view class="font-24 pb-4">
						剩余支付时间：
						<count-down className="d-inline-block font-20" @finish="payTimeEnd" v-slot="{ times }" :time="payInfo.orderCancelCountdownEndTime" :custom="true">
							<!-- 解决小程序中插槽内容不加载：添加占位标签&&延迟修改渲染内容 -->
							<!-- #ifdef MP -->
							<view class="w-0 h-0">{{ slotPlace }}</view>
							<!-- #endif -->
							<text v-if="times.days > 0">{{ times.days }}天</text>
							<text v-if="times.hours > 0">{{ times.hours }}时</text>
							<text>{{ times.minutes }}分</text>
							<text>{{ times.seconds }}秒</text>
						</count-down>
					</view>
				</view>
			</view>
			<!-- 业务单号 -->
			<view class="bg-white px-2 mt-2">
				<view class="d-flex a-center" style="padding: 24rpx 0;">
					<text class="item-b">业务单号：</text>
					<text class="flex-1 line-clamp1">{{ payInfo.businessOrderNumberList.join() }}</text>
				</view>
				<view class="d-flex a-center" style="padding-bottom: 24rpx;">
					<text class="item-b">交易信息：</text>
					<text class="flex-1 line-clamp1">{{ payInfo.subjectList.join() }}</text>
				</view>
			</view>

			<view class="bg-white mt-2 px-2">
				<radio-group @change="changePay">
					<label class="d-flex j-sb a-center pt-2 pb-2 font-28 border-bottom border-f8" v-for="(payItem, index) in payTypeList" :key="index">
						<view class="flex-center">
							<view class="w-60r h-100 mr-2">
								<text
									class="iconfont"
									:class="[payTypeIcons[payItem.payTypeId][0]]"
									:style="{ color: payTypeIcons[payItem.payTypeId][1], fontSize: `60rpx` }"
									v-if="!$u.test.isEmpty(payTypeIcons[payItem.payTypeId])"
								></text>
							</view>
							<text class="flex-1">{{ payItem.payTypeName }}</text>
						</view>
						<radio :value="payItem.payTypeId" class="scale-08" :checked="curPayType == payItem.payTypeId" :color="themes.color"></radio>
					</label>
				</radio-group>
			</view>
			<view class="px-2 position-fixed safearea-bb w-100 bottom-0">
				<ls-button className="but-main h-80r my-2" loading text="确认支付" :asyncFunction="surePay" :options="{ cl: '#FFF', br: '100', fs: '30' }" />
			</view>
		</view>
		<ls-empty className="center-xy" :title="paging.errMsg" :paging="paging" />
		<!-- #ifdef H5 -->
		<view class="" v-html="payDatas" v-if="payDatas&&curPayType=='ALI_PAY'"></view>
		<u-popup v-model="showWeiXinAliPay" mode="center" border-radius="14" width="80%" :key="payDatas">
			<view class="p-4 font-24 w-100">
				<view class="flex-center font-32 font-weight mb-4">请使用其它浏览器打开以下链接进行支付</view>
				<view class="w-100 px-2 text-pre-wrap overflow-h" style="max-height: 300rpx;">{{ payDatas }}</view>
				<view class="flex-center">
					<view class="weixin-tip-img" :class="$utils.getUa().isApple ? 'iphone' : 'android'"></view>
					<view class="weixin-tip"></view>
				</view>
				<view class="flex-center mt-2">
					<view class="flex-1 py-2 border border-e4 rounded-10 mr-2 text-center" @click="showWeiXinAliPay = false">取消支付</view>
					<view class="bg-main border border-main flex-1 py-2 rounded-10 text-fff text-center" @click="$stringUtils.lsCopy(payDatas)">复制链接</view>
				</view>
				<view class="font-24 mt-2 text-main w-100 text-center" v-if="payInfo.orderCancelCountdownEndTime">
					订单剩余支付时间
					<count-down className="d-inline-block font-20" @finish="payTimeEnd" v-slot="{ times }" :time="payInfo.orderCancelCountdownEndTime" :custom="true">
						<text v-if="times.days > 0">{{ times.days }}天</text>
						<text v-if="times.hours > 0">{{ times.hours }}时</text>
						<text>{{ times.minutes }}分</text>
						<text>{{ times.seconds }}秒</text>
					</count-down>
				</view>
			</view>
		</u-popup>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<!-- 易宝支付宝支付专用 -->
		<u-popup v-model="showWeiXinAliPay" mode="center" border-radius="14" width="80%" :key="payDatas" @open="painterOpen">
			<view class="p-4 font-24 w-100">
				<view class="flex-center font-32 font-weight mb-4">等待支付中...</view>
				<view class="flex-col-center">
					<text class="mt-2 text-999">
						{{ curPayType == 'YEEPAY_ALI_PAY' ? '可复制链接用浏览器识别后支付' : '请复制链接在微信中访问或者用微信扫二维码支付' }}
					</text>
					<!-- <l-painter width="400rpx" height="400rpx" :board="haiBaoData" isRenderImage isH5PathToBase64 @success="shareImg = $event" /> -->
					<LimePainter v-if="isPainterOk" :board="haiBaoData" isCanvasToTempFilePath @success="shareImg = $event"/>
				</view>
				<view class="font-24 mt-2 text-main w-100 text-center" v-if="payInfo.orderCancelCountdownEndTime">
					订单剩余支付时间
					<count-down className="d-inline-block font-24" @finish="payTimeEnd" v-slot="{ times }" :time="payInfo.orderCancelCountdownEndTime" :custom="true">
						<text v-if="times.days > 0">{{ times.days }}天</text>
						<text v-if="times.hours > 0">{{ times.hours }}时</text>
						<text>{{ times.minutes }}分</text>
						<text>{{ times.seconds }}秒</text>
					</count-down>
				</view>
				<view class="flex-center mt-2">
					<view class="flex-1 py-2 border border-e4 rounded-10 mr-2 text-center" @click="showWeiXinAliPay = false">取消支付</view>
					<view class="bg-main border border-main flex-1 py-2 rounded-10 text-fff text-center mr-2" @click="eventSave" v-if="curPayType == 'YEEPAY_WX_PAY'">
						保存图片
					</view>
					<view class="bg-main border border-main flex-1 py-2 rounded-10 text-fff text-center" @click="$stringUtils.lsCopy(payDatas)">复制链接</view>
				</view>
			</view>
		</u-popup>
		<!-- #endif -->
	</view>
</template>

<script>
import { mapState } from 'vuex';
import platformPayto from '@/service/payTo.js'; // 调用支付
import { orderApi } from '@/api/ModulesOrder.js';
import countDown from '@/components/common/countdown/count-down.vue';
import LimePainter from '@/components/l-painter-new/l-painter/l-painter.vue';
import { appToken } from '@/utils/Cache.js';

export default {
	components: { countDown, LimePainter },
	data() {
		return {
			payDatas: '', // 支付成功返回的
			payParams: {},
			curPayType: 'FREE_PAY',
			payInfo: {
				// 支付信息
				payTypeList: [], // 支付类型
				businessOrderNumberList: [], // 业务单号
				subjectList: [] // 交易信息
			},
			altPayImgCue: false, // 支付宝支付提示
			platform: '', // 用户手机系统类型 安卓、苹果
			payTypeIcons: {
				FREE_PAY: ['icon-mianfei', '#40CDA9'], // 免费支付
				ALI_PAY: ['icon-zhifubao', '#0CAEEF'], // 支付宝支付
				WX_PAY: ['icon-weixinzhifu', '#01CA02'], // 微信支付
				SIMULATE_PAY: ['icon-qianbao1', '#FEB347'], // 模拟支付
				GNETE_PAY: ['icon-yinhangka', '#0CAEEF'], // 银联支付
			},
			paging: {
				status: 'loading',
				error: false, // 是否错误
				errMsg: '暂无数据',
				emptylist: false // 是否显示列表为空时的样式
			},
			showWeiXinAliPay: false, // 如果是微信端打开支付宝支付或者APP端易宝支付宝支付，并且请求接口成功，
			timeOut: '',
			haiBaoData: {}, // 易宝支付宝/微信支付专用(链接的支付二维码)
			shareImg: '', // 支付二维码
			timer: null,
			slotPlace: '',
			isPainterOk: false,
		};
	},
	computed: {
		...mapState(['userInfo']),
		payTypeList() {
			return this.payInfo.payTypeList.filter((item, index) => {
				if (this.$utils.getUa().isMP && (item.payTypeId == 'YEEPAY_ALI_PAY' || item.payTypeId == 'ALI_PAY')) {
					return;
				} else {
					return item;
				}
			});
		}
	},
	watch: {
		showWeiXinAliPay(newValue) {
			if (!newValue) {
				// clearInterval(this.timeOut);
			}
		}
	},
	onLoad(option) {
		this.payParams = option;
		if (option.orderNumber) {
			this.payParams.orderNumber = JSON.parse(decodeURIComponent(option.orderNumber))
		}
		// 如果是APP端选择了易宝微信支付，调起小程序，则只执行surePay()方法--只有APP端拉起微信小程序支付才会传payType值
		if (!(this.payParams.payType == 'YEEPAY_WX_PAY')) {
			this.toPay();
		}
		// #ifdef MP
		clearTimeout(this.timer)
		this.timer = setTimeout(() => {
			this.slotPlace = '     '
		}, 500)
		// #endif
	},
	onShow() {
		// #ifdef MP
		// 如果是APP端选择了易宝微信支付，就直接调起微信小程序进行支付--只有APP端拉起微信小程序支付才会传payType值
		this.$nextTick(() => {
			if (this.payParams.payType == 'YEEPAY_WX_PAY') {
				this.curPayType = this.payParams.payType
				this.surePay(this.curPayType)
			}
		})
		// #endif
	},
	mounted() {},
	destroyed() {
		clearInterval(this.timeOut);
	},
	methods: {
		payTimeEnd() {
			uni.redirectTo({ url: `/ModuleOrder/orderList/orderList` });
		},
		changePay(e) {
			this.curPayType = e.detail.value;
		},

		// 发起支付
		toPay() {
			this.paging = {
				status: 'loading',
				error: false, // 是否错误
				errMsg: '暂无数据',
				emptylist: false // 是否显示列表为空时的样式
			};
			orderApi
				.payOrder({
					businessOrderNumberList: this.payParams.orderNumber,
					settlementType: this.payParams.settlementType
				})
				.then(res => {
					if (res.code) {
						this.payInfo = res.data;
						if (this.payInfo.amount == 0) {
							this.curPayType = 'FREE_PAY';
							this.surePay();
							return;
						}
						setTimeout(() => {
							if (this.payTypeList && this.payTypeList.length) {
								this.curPayType = this.payTypeList[0].payTypeId;
							}
						},100)
					} else {
						this.paging.errMsg = res.msg;
					}
				})
				.catch(err => {
					this.paging.error = true;
					this.paging.errMsg = err.response && err.response.data && err.response.data.msg;
				})
				.finally(res => {
					this.paging.status = 'noMore';
					if (!this.$checkInfo([{ type: 'hasValue', value: this.payInfo.businessOrderNumberList }])) {
						this.paging.emptylist = true;
					}
				});
		},
		// 返回
		goback() {
			uni.showModal({
				title: '是否放弃付款？',
				success: res => {
					if (res.confirm) {
						uni.redirectTo({ url: `/ModuleOrder/orderList/orderList` });
					} else if (res.cancel) {
					}
				}
			});
		},
		// 确认支付
		surePay(payType) {
			return new Promise((resolve) => {
				this.platform = uni.getSystemInfoSync().platform;
				uni.showLoading({ title: '正在支付...', mask: true });
				// 如果是【APP端易宝微信支付】，则直接拉起小程序
				if(this.$utils.getUa().isAPP && this.curPayType == 'YEEPAY_WX_PAY'){
					this.setTimeout(); // 打开定时器每两秒请求一次接口看有没有支付成功
					setTimeout(() => {
						// 30分钟内还未支付的话,终止
						uni.hideLoading();
						return resolve()
						clearInterval(this.timeOut);
					},1800000)
					
					// 唤醒微信app并访问H5页面(但要申请第三方ticket)
					// plus.runtime.openURL(`weixin://dl/business/?ticket=${res.data.paymentResult}`);
									
					// 找出分享到微信端
					plus.share.getServices(
						(shareRes) => {
							var shares = {};
							for (var i = 0; i < shareRes.length; i++) {
								var t = shareRes[i];
								shares[t.id] = t;
								// console.log(t.id);//sinaweibo,qq,weixin
							}
							var sweixin = shares['weixin'];
							// console.log('sweixin:',sweixin);//{ "id": "weixin", "description": "微信", "authenticated": true, "accessToken": "", "nativeClient": true }
							const parmas = {
								orderNumber:encodeURIComponent(JSON.stringify(this.payParams.orderNumber)),
								settlementType:this.payParams.settlementType,
								payType:this.curPayType,
							}
							const url = `/ModuleOrder/submitOrder/payOrder${this.$u.queryParams(parmas)}`
							// console.log('url:',url);
							// 拉起微信小程序
							sweixin
								? sweixin.launchMiniProgram({
									id: this.$config.wxOriginalId, // https://mp.weixin.qq.com/里【设置】-【帐号信息】->【原始ID】
									path: url
								})
								: plus.nativeUI.alert('当前环境不支持微信操作!');
							return resolve()
						},
						(e) => {
							return resolve()
							console.log('获取分享服务列表失败：' + e.message);
						}
					);
				// 如果是【APP端易宝微信支付】以外的支付
				}else{
					platformPayto.pay(this.curPayType, this.payParams.orderNumber, this.payParams.settlementType).then(res => {
						// platformPayto.orderPay(payTypeValue, 1, passwordCallback, subNumbers).then(res => {
						console.log('支付成功, 业务回调: %o', res);
						if (res.success) {
							uni.hideLoading();
							// 说明返回的类型是表单, 需要前端发起请求真实支付 处理成功后由后端重定向到支付结果:小程序没有form表单
							if (res.dataType == 'form') {
								// this.payDatas = res.data.prepayResult; 
								// this.payDatas = res.data.paymentResult; //后端加密了paymentResult,在payTo.js中将解密后的内容放在res.form中
								this.payDatas = res.form;
								// 如果是微信端打开支付宝支付
								if (this.$utils.getUa().isWeixin && (this.curPayType == 'YEEPAY_ALI_PAY' || this.curPayType == 'ALI_PAY')) {
									// const jumpAddress = `/ModuleOrder/submitOrder/wxAliPay?payData=${encodeURIComponent(res.data.paymentResult)}&subSettlementSn=${encodeURIComponent(res.data.paySettlementSn)}`
									// location.replace(jumpAddress)// 由于IOS上点右上角的复制链接时，用uni.redirectTo跳转的话，?后面的参数是复制不了的，所以要用到location.replace()方法
									// // uni.redirectTo({url: `/ModuleOrder/submitOrder/wxAliPay?payData=${encodeURIComponent(res.data.paymentResult)}&subSettlementSn=${encodeURIComponent(res.data.paySettlementSn)}`});
									this.setTimeout(); // 打开定时器每两秒请求一次接口看有没有支付成功
									this.$nextTick(() => {
										// 易宝支付宝支付,res.data.paymentResult是带有HTTP开头的链接
										if (this.curPayType == 'YEEPAY_ALI_PAY') {
											this.showWeiXinAliPay = true; // 打开popup弹框
										}
										// 支付宝支付,res.data.paymentResult是带有<form>表单格式
										if (this.curPayType == 'ALI_PAY') {
											document.forms[0].submit();
										}
									})
								} else {
									this.$nextTick(() => {
										if(this.curPayType == 'YEEPAY_ALI_PAY'){
											window.location.href = res.data.paymentResult;
											// window.open(res.data.paymentResult);
										}else{
											document.forms[0].submit();
										}
									});
								}
							// 否则返回的是JSON
							} else {
								// 如果是APP及易宝支付宝支付,则跳H5页面上访问支付宝的易宝链接，在H5页面上拉起支付宝支付
								if (this.$utils.getUa().isAPP && this.curPayType == 'YEEPAY_ALI_PAY') {
									this.payDatas = res.data.paymentResult;
									const haiBaoDataTemp = {
										css: {
											width: '400rpx',
											height: '400rpx',
											borderRadius: '16rpx',
											background: '#fff',
										},
										// width: '400rpx',
										// height: '400rpx',
										// radius: '16rpx',
										// background: '#fff',
										views: [
											{
												type: 'qrcode',
												text: res.data.paymentResult,
												css: {
													width: '380rpx',
													height: '380rpx',
													color: '#000',
													border: '20rpx solid #fff'
												}
											}
										]
									};
									this.$set(this, 'haiBaoData', haiBaoDataTemp);
									this.setTimeout(); // 打开定时器每两秒请求一次接口看有没有支付成功
									this.$nextTick(() => {
										this.showWeiXinAliPay = true; // 打开popup弹框
										plus.runtime.openWeb(res.data.paymentResult);
									});
								// 如果是正常支付(APP或小程序)
								} else {
									// 如果是APP端选择了易宝微信支付，调起小程序支付成功后，
									if (payType == 'YEEPAY_WX_PAY') {
										const payParams = {
											orderNumber:encodeURIComponent(JSON.stringify(this.payParams.orderNumber)),// 【支付失败】后点击【重新支付】用
											settlementType:this.payParams.settlementType,// 【支付失败】后点击【重新支付】用
											amount:this.payInfo.amount,// 【支付失败】后点击【重新支付】用
											subSettlementSn:res.data.paySettlementSn,
											payType:payType
										};
										uni.redirectTo({
											url: `/ModuleOrder/submitOrder/orderPayResult${this.$u.queryParams(payParams)}`
										});
									}else{
										const payParams = {
											orderNumber:encodeURIComponent(JSON.stringify(this.payParams.orderNumber)),// 【支付失败】后点击【重新支付】用
											settlementType:this.payParams.settlementType,// 【支付失败】后点击【重新支付】用
											amount:this.payInfo.amount,// 【支付失败】后点击【重新支付】用
											subSettlementSn:res.data.paySettlementSn,
										};
										uni.redirectTo({
											url: `/ModuleOrder/submitOrder/orderPayResult${this.$u.queryParams(payParams)}`
										});
									}
								}
							}
						} else {
							uni.showToast({ title: res.msg, duration: 2000, icon: 'none' });
						}
					}).catch(res => {
						// 如果没有微信授权
						if (res.code == -1000) {
							// #ifdef MP
							appToken.toLogin()
							// #endif
							// #ifdef H5
							if(this.$utils.getUa().isWeixin){
								appToken.toLogin()
							}
							// #endif
						}
					}).finally(() => { return resolve() })
				}
			})
		},
		setTimeout() {
			clearInterval(this.timeOut);
			this.timeOut = setInterval(() => {
				// 获取成功的订单数据
				orderApi.orderSuccess(this.payParams.orderNumber).then(respond => {
					if (respond.code == 1) {
						if (respond.data.state === 1) {
							this.showWeiXinAliPay = false;
							uni.showToast({
								title: '支付成功',
								mask: true,
								complete: () => {
									setTimeout(() => {
										const payParams = {
											orderNumber:encodeURIComponent(JSON.stringify(this.payParams.orderNumber)),// 【支付失败】后点击【重新支付】用
											settlementType:this.payParams.settlementType,// 【支付失败】后点击【重新支付】用
											amount:this.payInfo.amount,// 【支付失败】后点击【重新支付】用
											subSettlementSn:respond.data.settlementSn,
										};
										uni.redirectTo({
											url: `/ModuleOrder/submitOrder/orderPayResult${this.$u.queryParams(payParams)}`
										});
									}, 1500);
								}
							});
						}
					}
				});
			}, 2000);
		},

		// 保存图片(易宝支付专用)
		eventSave() {
			uni.saveImageToPhotosAlbum({
				filePath: this.shareImg,
				success: res => {
					if (res.errMsg == 'saveImageToPhotosAlbum:ok') {
						uni.showToast({
							title: '保存图片成功',
							duration: 2000
						});
					}
				},
				fail: err => {
					if (!err.errMsg.includes('cancel')) {
						uni.showToast({
							title: '检测到您未打开“相册”权限，是否前往开启',
							duration: 2000
						});
					}
				}
			});
		},
		
		// 用于小程序做画板渲染 否则小程序上会出现两张图片 一张其实是canvas引起的bug
		// 因此要确保popup渲染完后再v-if lime-painter
		painterOpen() {
			this.$nextTick(() => {
				this.isPainterOk = true;
			})
		}
	}
};
</script>

<style>
page {
	background-color: var(--backgroundcolor);
}
</style>

<style scoped lang="scss">
// start--H5微信浏览器上打开支付的弹框
.weixin-tip {
	box-sizing: border-box;
	position: absolute;
	bottom: 40px;
	right: 20px;
	width: 265px;
	padding: 75px 0 0;
	text-align: right;
	margin-bottom: 30px;
	font-size: 14px;
	background: url()
		no-repeat right bottom;
	background-size: 45px 68px;
	transform: rotate(180deg) rotateY(180deg);
}

.weixin-tip-img::after {
	display: block;
	margin: 15px auto;
	content: ' ';
	background-size: cover;
}

.iphone::after {
	width: 150px;
	height: 150px;
	background-image: url();
}

.android::after {
	width: 173px;
	height: 240px;
	background-image: url();
}
// end--H5微信浏览器上打开支付的弹框
</style>
